/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package controllers;  
import play.*;
import play.mvc.*;

import java.util.*;
import models.*;

@With(Secure.class)
public class Admin extends Controller {

    @Before
    static void setConnectedUser(){
        if(Security.isConnected()){
            User user = User.find("byEmail", Security.connected()).first();
            renderArgs.put("user", user.fullname);
        }
    }
    
    public static void index(){
        String user = Security.connected();
        List<Post> posts = Post.find("author.email", user).fetch();
        render(posts);
    }
    
    public static void form(Long id){
       if(id != null){
           Post post = Post.findById(id);
           render(post);
       }
        render();
    }
    
    public static void save(Long id, String title, String content, String tags){
       Post post;
       if(id == null)
       {
       //Creamos el post
       User author = User.find("byEmail", Security.connected()).first();
       post = new Post(author,title,content);
       } else {
           //Revisar post
           post =Post.findById(id);
           //Edit
           post.title = title;
           post.content=content;
           post.tags.clear();
       }
       
       
       //Asignamos los tags
       for(String tag: tags.split("\\s+")){
           if(tag.trim().length()>0){
               post.tags.add(Tag.findOrCreateByName(tag));
           }
       }
       
       //Validamos
       validation.valid(post);
       if(validation.hasErrors()){
           render("@form", post);
       }
       //Salvamos
       post.save();
       index();
    }
    
}